// pages/coupon/points.js
const api = require('../../utils/api');
const utils = require('../../utils/index');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs: ['全部', '收入', '支出'],
    tabActive: 0,
    pointsStats: {
      earned: 0,
      used: 0
    },
    pointsList: [],
    filteredList: [],
    page: 1,
    pageSize: 20,
    hasMore: true,
    loading: false,
    refreshing: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 设置页面标题
    wx.setNavigationBarTitle({
      title: '积分明细',
    });
    
    // 加载积分明细数据
    this.loadPointsLogs();
  },

  /**
   * 返回上一页
   */
  onTapBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  /**
   * 切换标签页
   */
  onTabChange(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      tabActive: index,
      page: 1,
      hasMore: true,
      pointsList: [],
      filteredList: []
    });
    this.loadPointsLogs();
  },

  /**
   * 根据当前标签筛选积分列表
   */
  filterPointsList() {
    let filteredList = [];
    
    switch(this.data.tabActive) {
      case 0: // 全部
        filteredList = this.data.pointsList;
        break;
      case 1: // 收入
        filteredList = this.data.pointsList.filter(item => item.points > 0);
        break;
      case 2: // 支出
        filteredList = this.data.pointsList.filter(item => item.points < 0);
        break;
    }
    
    this.setData({
      filteredList: filteredList
    });
  },

  /**
   * 获取积分明细数据
   */
  loadPointsLogs() {
    // 如果已经没有更多数据或者正在加载中，直接返回
    if (!this.data.hasMore || this.data.loading) return;
    
    this.setData({ loading: true });
    
    // 构建请求参数
    let params = {
      page: this.data.page,
      page_size: this.data.pageSize
    };
    
    // 根据当前标签页筛选不同类型的积分记录
    if (this.data.tabActive === 1) { // 收入
      params.type = 'income';
    } else if (this.data.tabActive === 2) { // 支出
      params.type = 'expense';
    }
    
    // 显示加载中
    if (!this.data.refreshing) {
      wx.showLoading({
        title: '加载中...',
      });
    }
    
    // 调用接口获取积分记录
    api.user.getPointsLogs(params)
      .then(res => {
        if (res.success) {
          // 处理获取到的数据
          const logsList = res.data.list || [];
          
          // 格式化数据
          const formattedList = logsList.map(item => {
            return {
              id: item.id,
              time: utils.formatTimestampWithTime(item.created_at),
              reason: item.description,
              points: item.points,
              type: item.type,
              before_points: item.before_points,
              after_points: item.after_points
            };
          });
          
          // 计算收入和支出统计
          const stats = res.data.stats || {};
          
          // 更新数据
          this.setData({
            pointsList: this.data.page === 1 ? formattedList : [...this.data.pointsList, ...formattedList],
            pointsStats: {
              earned: stats.total_earned || 0,
              used: stats.total_used || 0
            },
            page: this.data.page + 1,
            hasMore: logsList.length >= this.data.pageSize
          });
          
          // 筛选数据
          this.filterPointsList();
        } else {
          wx.showToast({
            title: res.message || '获取积分记录失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取积分记录失败:', err);
        wx.showToast({
          title: '获取积分记录失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
        this.setData({ 
          loading: false,
          refreshing: false
        });
      });
  },
  
  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
      pointsList: [],
      filteredList: [],
      refreshing: true
    });
    
    this.loadPointsLogs();
    wx.stopPullDownRefresh();
  },
  
  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.hasMore) {
      this.loadPointsLogs();
    }
  }
})